package com.study.common;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.script.DigestUtils;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import static org.apache.logging.log4j.util.Strings.isEmpty;

@Slf4j
public class AlgorithmUtil {

    /**
     * <p>递归查找文件</p>
     *
     * @param dirName 文件目录
     * @param names 文件集合
     */
    public static void getFileName(String dirName, List<String> names) {
        File file = new File(dirName);
        File[] files = file.listFiles();
        if (ObjectUtils.isNotEmpty(files)) {
            for (File file1 : files) {
                if (file1.isDirectory()) {
                    getFileName(file1.getPath(), names);
                } else {
                    String fileName = dirName + "//" + file1.getName();
                    names.add(fileName);
                }
            }
        } else {
            throw new BusinessException("没有找到目录下文件...");
        }
    }

    public static void testFile(){
        String dirName = "C:\\ertdsf\\javaT";
        List<String> list = new ArrayList<>();
        getFileName(dirName,list);
        for (String s : list) {
            System.out.println(s);
        }
    }

    /**
     * md5 加密 32
     * @param string 加密串
     * @return String
     */
    public static String getMd5(String string) {
        if (isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result.append(temp);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

}
